package com.hsxc.cdz.controller.appController;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hsxc.cdz.base.bean.Bill;
import com.hsxc.cdz.base.bean.MyUser;
import com.hsxc.cdz.mgmt.GlobalManager;
import com.hsxc.cdz.trans.payment.gzhpay.PrePay;

import net.sf.json.JSONObject;

/**
 * @author 作者 : 陈钊
 * @version 创建时间：2016年8月30日 上午11:29:15 类说明：直接支付
 */
@Controller("pay")
@RequestMapping("/app")
public class PayController {

	Logger logger = LoggerFactory.getLogger(PayController.class);
	@RequestMapping(value = "/pay", method = RequestMethod.GET)
	@ResponseBody
	public Object pay(@RequestParam("billNo") String billNo, HttpServletRequest httpServletRequest) throws UnsupportedEncodingException {
		logger.info("STRAT TO PAY"+"BILLNO IS "+billNo);
		JSONObject result = new JSONObject();
		Bill bill = GlobalManager.billManager.getBillByBillNO(billNo);
		result.put("success", true);
		Subject AppUser = SecurityUtils.getSubject();
		if(AppUser==null|| AppUser.getPrincipal() == null){
			result.put("added", false);
			result.put("errcode", MyUser.NO_LOGIN);
			result.put("message", "没有登录");
			return result;
		}
		if (bill != null) {
			if (bill.getState() != Bill.PAYED) {
				JSONObject jsonObject = PrePay.order(bill.getBillNO(), bill.getUserNO(),
						httpServletRequest.getRemoteAddr(), 4);
				if (jsonObject.getInt("code") == 0) {
					result.put("errcode", 0);
					result.put("message", jsonObject);
					return result;
				} else {
					result.put("errcode", 1);
					result.put("message", "下单失败");
					return result;
				}
			}else{
				result.put("errcode",3);
				result.put("message","该账单已经支付");
				return result;
			}

		} else {
			result.put("errcode", 2);
			result.put("message", "账单不存在");
			return result;
		}
	}
}
